/* 调用短信发送接口  xuqing 1.0   sxw 1.1 
 * 使用方法：
 * 先写一个<button id='btn'></button>
 * $('#btn').timer({
 * url:ajax地址，类型string,
 * inputPhone:填写手机号或邮箱的input，类型object,
 * verifyImgInput:填写图形验证码的input，类型object
 * inputToken:填写token的input，类型object
 * method:发送邮件还是短信
 * before:
 * onError:手机号码验证失败后的回调函数，类型function
 * after:
 * clickClass:鼠标点击计时器后出发的样式，类型string,
 * time:计时器的秒数，类型number
})
* */
var timerLocked=false;
$.fn.timer = function(setting) {
    	
	if(!timerLocked){
		timerLocked=true;
		var defaults={
	        url:"",
	        time:60,
	        before:function(){},
	        after:function(){},
	        onCorrect:function(){},
	        onError:function(){}


		};	
		var setting = $.extend(defaults,setting);
		var mobileReg=/^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/;
		var emailReg=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;

        console.log(this +"start timing");
		//this.html('获取验证码')
			//
		this.hover(function() {
				$(this).css({
					cursor: 'pointer'
				})
			})

		var me = this;
		timerLocked=true;
	    //倒计时
		var clock = function(obj) {
			    
				obj.i = setting.time;
				obj.timer = setInterval(function() {
					obj.i--;
						var str = obj.i + "秒后重新发送";
					obj.attr('disabled', 'disabled');
					obj.html(str);
					if (obj.i == 0) {
						timerLocked=false;
						clearInterval(obj.timer);
						obj.removeClass(setting.clickClass);
						obj.i = setting.time;
						obj.removeAttr('disabled');
						obj.html('获取验证码');
						//obj.one("click",sendSMS);
					}else{
						return false;
					}
				}, 1000)
		}
		//
		sendSMS(me);
	}

	function sendSMS(me){
		setting.before();
		var data = {};
		if(setting['inputPhone']!=null){

			if(setting['inputPhone'] == '_sess'){
				//没有传入手机，后端按session处理
				data.cellphone = setting['inputPhone'];
			} else {
				if(setting['method'] == 'sms'){
					if(mobileReg.test(setting['inputPhone'].val())==false){
						setting.onError(setting['inputPhone'],me);
						timerLocked=false;
						return ;
					} else {
						setting.onCorrect(setting['inputPhone'],me);
						data.cellphone = setting['inputPhone'].val();
					}
				} else {
					if(emailReg.test(setting['inputPhone'].val())==false){
						setting.onError(setting['inputPhone'],me);
						timerLocked=false;
						return ;
					} else {
						setting.onCorrect(setting['inputPhone'],me);
						data.cellphone = setting['inputPhone'].val();
					}
				}
			}	

		}

		if(setting['verifyImgInput']!=null){//判断图像验证码
			if(!!!setting['verifyImgInput'].val()){
				setting.onError(setting['verifyImgInput']);
				timerLocked=false;
				return ;
			}else{
				setting.onCorrect(setting['verifyImgInput']);
				vCodeVal=setting['verifyImgInput'].val();
				data.imgCode = vCodeVal;
			}
		}
		var val = $(me).attr('token');
		if(val){
			var idx = $(me).attr('id');
			idx = 32 - parseInt(idx.split('_')[0])
			var part1 = val.substring(0, idx);
			var part2 = val.substring(idx, val.length);
			var token = part2 + part1;
		} else {
			var token = '';
		}
		data.token = token;
		data.method = setting.method;
		var elem = me;
		$.ajax({
			url: setting.url,
			data:data,
			dataType:"json",
			success: function(data){
				if(data.status){
					if(data.status==-1){
						    //发送失败
						    $(elem).addClass(setting.clickClass);
						    $(elem).removeClass(setting.clickClass);
						    if(setting['verifyImg']){
						  		setting['verifyImg'].trigger('click');
						    }
						    showModal({msg:data.msg});
						    timerLocked=false;
						    //clock ($(elem));
					  }else{
					  	  //发送成功
					  	  	if(data.smscode){
						  		$(elem).parents('form').find('[name^=smscode]').val(data.smscode);
						  	}
						  	if(setting.after != undefined &&setting.after!=null && typeof setting.after == 'function'){
								setTimeout(setting.after(data),(setting.time-1) * 1000);
							}
							$(elem).addClass(setting.clickClass);
							$(elem).unbind("click",sendSMS);
							clock ($(elem));
					  }
					return;
				}
				//兼容error
				if(data.result){
					//成功
					if(setting.after != undefined &&setting.after!=null && typeof setting.after == 'function'){
						setTimeout(setting.after(data),(setting.time-1) * 1000);
					}
					$(elem).addClass(setting.clickClass);
					$(elem).unbind("click",sendSMS);
					clock ($(elem));
				} else {
					$(elem).addClass(setting.clickClass);
					$(elem).removeClass(setting.clickClass);
					if(setting['verifyImg']){
					  		setting['verifyImg'].trigger('click');
					}
					showModal({msg:data.errorMsg});
					clock ($(elem));
				}

			},
            error:function(data) {
                if (data && data.status && data.status == 520) {
                    var _txt = eval("'" + data.statusText + "'");
                    showModal({msg:_txt});
                }
            }
		});


	}		//
}
$.fn.timerclock = function(setting, func){
	var obj = this;
	obj.i = setting.time;
		obj.timer = setInterval(function() {
			obj.i--;
				var str = obj.i + "秒后重新发送";
			obj.attr('disabled', 'disabled');
			obj.html(str);
			if (obj.i == 0) {
				timerLocked=false;
				clearInterval(obj.timer);
				obj.removeClass(setting.clickClass);
				obj.i = setting.time;
				obj.removeAttr('disabled');
				obj.html(setting.html);
				obj.on('click',func);
			}else{
				return false;
			}
		}, 1000)
}